package com.hph.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hph.health.common.ErrorCode;
import com.hph.health.constant.CommonConstant;
import com.hph.health.exception.BusinessException;
import com.hph.health.model.dto.user.UserQueryRequest;
import com.hph.health.model.entity.User;
import com.hph.health.model.vo.user.LoginUserVO;
import com.hph.health.model.vo.user.UserVO;
import com.hph.health.service.UserService;
import com.hph.health.mapper.UserMapper;
import com.hph.health.utils.SqlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author 19378
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-03-27 20:32:59
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Override
    public long userRegister(String userId, String userPassword, String checkPassword, String userType) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userId, userPassword, checkPassword, userType)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userId.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        synchronized (userId.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            //2. 加密
            //获取盐值
            String salt = UUID.randomUUID().toString().toUpperCase();
            //将密码和盐值作为一个整体来进行加密处理
            String md5Password = getMD5Password(userPassword, salt);
            // 3. 插入数据
            User user = new User();
            user.setUserId(userId);
            user.setSalt(salt);
            user.setPassword(md5Password);
            user.setUserType(userType);
            user.setUserStats(1);
            user.setGender(1);
            user.setUserName("默认昵称");
            user.setRealName("真实姓名");
            user.setPhone("10086");
            user.setUserProfile("这个人很懒，没改自己的个性");
            user.setEmail("默认邮箱");
            user.setUserAvatar("src/assets/file/user/默认.jpg");
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }

    }

    @Override
    public long userAdd(User user) {
        // 1. 校验
        if (StringUtils.isAnyBlank(user.getUserId(), user.getUserName(), user.getUserType())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (user.getUserId().length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        synchronized (user.getUserId().intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", user.getUserId());
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            user.setPassword("686EB35235B51B203552CF577B6E3EF7");
            user.setSalt("322E5F5E-B042-48FF-876E-CFE350975A46");
            user.setUserStats(1);
            user.setGender(1);
            user.setUserName("默认昵称");
            user.setRealName("真实姓名");
            user.setPhone("10086");
            user.setUserProfile("这个人很懒，没改自己的个性");
            user.setEmail("默认邮箱");
            user.setUserAvatar("src/assets/file/user/默认.jpg");
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public LoginUserVO userLogin(String userId, String password) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userId, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userId.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        User user = this.baseMapper.selectOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        if (!(StringUtils.equals(user.getPassword(),getMD5Password(password,user.getSalt())))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码错误");
        }
        if(user.getUserStats() == 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"您的号已被封禁");
        }

        return this.getLoginUserVO(user);
    }

    @Override
    public Boolean updatePassword(Long Id, String oldPassword, String newPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(oldPassword, newPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (newPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新密码格式不对");
        }
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", Id);
        User user = this.baseMapper.selectOne(queryWrapper);
        String oldMd5Password = getMD5Password(oldPassword, user.getSalt());
        if(!oldMd5Password.equals(user.getPassword())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "旧密码错误");
        }
        String salt = UUID.randomUUID().toString().toUpperCase();
        //将密码和盐值作为一个整体来进行加密处理
        String md5Password = getMD5Password(newPassword, salt);
        user.setSalt(salt);
        user.setPassword(md5Password);
        boolean result = this.updateById(user);
        return result;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        String userId = userQueryRequest.getUserId();
        String userName = userQueryRequest.getUserName();
        String realName = userQueryRequest.getRealName();
        Integer gender = userQueryRequest.getGender();
        String email = userQueryRequest.getEmail();
        String phone = userQueryRequest.getPhone();
        String userProfile = userQueryRequest.getUserProfile();
        Integer userPoint = userQueryRequest.getUserPoint();
        Integer userLevel = userQueryRequest.getUserLevel();
        String userType = userQueryRequest.getUserType();
        Integer userStats = userQueryRequest.getUserStats();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(userId), "user_id", userId);
        queryWrapper.like(StringUtils.isNotBlank(userName), "user_name", userName);
        queryWrapper.like(StringUtils.isNotBlank(realName), "real_name", realName);
        queryWrapper.eq(gender != null, "gender", gender);
        queryWrapper.like(StringUtils.isNotBlank(email), "email", email);
        queryWrapper.like(StringUtils.isNotBlank(phone), "phone", phone);
        queryWrapper.like(StringUtils.isNotBlank(userProfile), "user_profile", userProfile);
        queryWrapper.eq(userPoint != null, "user_point", userPoint);
        queryWrapper.eq(userLevel != null, "user_level", userLevel);
        queryWrapper.eq(StringUtils.isNotBlank(userType), "user_type", userType);
        queryWrapper.eq(userStats != null, "user_stats", userStats);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /*定义一个md5算法的加密*/
    public String getMD5Password(String password, String salt) {
        //MD5加密算法方法的调用(进行三次加密)
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        //返回加密之后的密码
        return password;
    }
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }
}




